import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';
import { ResultUtils } from 'src/common/utils/result.utils';
import { Tag } from './tag.entity';
import { GetTagDto } from './dto/get-tag.dto';

@Injectable()
export class TagService {
  constructor(@InjectRepository(Tag) private tagRepository:Repository<Tag>){}
  async create(createTagDto: CreateTagDto) {
    const tag = await this.tagRepository.create(createTagDto);
    const result = await this.tagRepository.save(tag);
    return ResultUtils.success(result.id);
  }

  async findAll(query:GetTagDto,isAdmin:boolean) {
    let {limit,page} = query;
    const queryBuilder = this.tagRepository.createQueryBuilder('tag');
    if(!isAdmin){
      queryBuilder.loadRelationCountAndMap('tag.articleNum', 'tag.articles','atricle',(qb)=>qb.where('atricle.status=1')).andWhere('tag.status=:status',{status:1});
    }else{
      queryBuilder.loadRelationCountAndMap('tag.articleNum', 'tag.articles');
    }
    queryBuilder.orderBy('tag.sort','DESC').addOrderBy('tag.update_time','DESC');
    if(page) {
      if(!limit) {
        limit = 10
      }
      queryBuilder.take(limit).skip((page-1)*limit);
      const list = await queryBuilder.getManyAndCount();
      return ResultUtils.success({
        list:list[0],
        total:list[1]
      });
    }else {
      return ResultUtils.success(await queryBuilder.getMany());
    } 
  }

  async findOne(id: number,isAdmin:boolean) {
    const queryBuilder = this.tagRepository.createQueryBuilder('tag');
    if(!isAdmin) {
      queryBuilder.loadRelationCountAndMap('tag.articleNum', 'tag.articles','atricle',(qb)=>qb.where('atricle.status=1')).andWhere('tag.status=:status',{status:1});
    }else{
      queryBuilder.loadRelationCountAndMap('tag.articleNum', 'tag.articles');
    }
    queryBuilder.andWhere({id})
    return ResultUtils.success(await queryBuilder.getOne());
  }

  async update(id: number, updateTagDto: UpdateTagDto) {
    const tag = await this.tagRepository.findOne({ where: {id} });
    const newTag = this.tagRepository.merge(tag,updateTagDto);
    return ResultUtils.success(await this.tagRepository.save(newTag));
  }

  async remove(id: number) {
    await this.tagRepository.delete(id);
    return ResultUtils.success();
  }
}
